/*
 * @Author: long
 * @Date: 2023-01-30 16:11:34
 * @LastEditors: long
 * @LastEditTime: 2023-01-30 17:39:43
 * @Description: 承诺池 (即有待请求接口100个，限制每次只能发出10个。即同一时刻最多有10个正在发送的请求)
 */
class RequirePool {
    constructor(funcArray,limit = 100) {
        const newfuncArray = funcArray.filter(item => { return  this.isPromise(item) })
        return this.PromiseAllLimit(newfuncArray,limit)
    }
    isPromise(p){
        if (typeof p === 'object' && typeof p.then === 'function') {
            return true;
        }
        return false;
    }
    PromiseAllLimit(funcArray, limit = 100) {
        funcArray = funcArray.filter(item => { return  this.isPromise(item) })

        let i = 0;
        const result = [];
        const executing = [];
        //判断是否是 Promise 函数
        const isPromise = (p) => { return this.isPromise(p); }
        const queue = function() {
            if (i === funcArray.length) return Promise.all(executing);
            const thatfunc = funcArray[i++];
            let p = thatfunc
            if(thatfunc && !isPromise(thatfunc)){
                p = thatfunc()
            }
            if(!isPromise(p)){
                console.error('非Promise函数！',p)
            }
            result.push(p);
            const e = p.then(() => executing.splice(executing.indexOf(e), 1));
            executing.push(e);
            if (executing.length >= limit) {
                return Promise.race(executing).then(
                    () => queue(),
                    e => Promise.reject(e)
                );
            }
            return Promise.resolve().then(() => queue());
        };
        return queue().then(() => Promise.all(result));
    }
}
export default (funcArray,concurrNum) => { return new RequirePool(funcArray,concurrNum) }

export const requirePool = (funcArray,concurrNum) => { return new RequirePool(funcArray,concurrNum) }

// test
// const promiseList = [
//     new Promise((resolve, reject) => {
//         resolve('李四1')
//     }),
//     new Promise((resolve, reject) => {
//         setTimeout(() => {
//             resolve('李四2')
//         },200)
//     }),
//     new Promise((resolve, reject) => {
//         resolve('李四3')
//     }),
//     new Promise((resolve, reject) => {
//         resolve('李四4')
//     })
    
// ]
// new RequirePool(promiseList,1).then(res => {
//     console.log("22222222222  ",res);
// })

